import { devDebug } from './utils/settings';

App({
  globalData: {
    userInfo: null,
  },
  onLaunch() {
    this.setDateExtra();
    this.setStringExtra();
    wx.cloud.init({ traceUser: true, env: 'cloud1-8gpofkhm4c548bd3' });
    if (!devDebug) this.getUserInfo();
  },
  setDateExtra() {
    Date.prototype.Format = function (format = 'yyyy-MM-dd hh:mm:ss') {
      var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
      }
      if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
        (this.getFullYear() + "").substr(4 - RegExp.$1.length));
      for (var k in o) if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
          RegExp.$1.length == 1 ? o[k] :
            ("00" + o[k]).substr(("" + o[k]).length));
      return format;
    }
  },
  async getUserInfo() {
    let { userInfo, errMsg } = await new Promise(resolve => {
      wx.cloud.callFunction({
        name: 'login',
        success: (r) => resolve(r.result),
      })
    });
    if (userInfo == null) {
      wx.reLaunch({
        url: `/pages/templates/404?errMsg=${errMsg}`,
      })
    } else {
      this.globalData.userInfo = userInfo;
      if (userInfo.role_id == 0) {
        wx.reLaunch({
          url: '/pages/admin/index',
        })
      } else if (userInfo.role_id != 3) {
        wx.hideTabBar({ animation: false })
        wx.switchTab({
          url: '/pages/user/mine',
        })
      }
    }
  },
  setStringExtra() {
    let urlAlphabet =
      'useandom26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
    String.prototype.nanoid = (size = 32) => {
      let id = '', i = size
      while (i--) {
        id += urlAlphabet[(Math.random() * 64) | 0]
      }
      return id
    }
  }
})
